package 文件操作.searchDirectory;
import java.io.*;
import java.util.Scanner;

public class SearchDirectory {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入目录路径");
        String srcPath = in.next();

        File file = new File(srcPath); // 文件路径
        if (! file.exists()) { // 如果不存在
            System.out.println("该路径不存在");
            return ;
        }
        // 如果不是目录
        if (! file.isDirectory()) {
            System.out.println("这路径下不是目录");
            return ;
        }

        System.out.println("请输入目标文件名");
        String srcName = in.next();


        // 正文
        searchDirectory(file, srcName);
    }

    private static void searchDirectory(File file, String srcName) {
        try {
            System.out.println(file.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        File[] files = file.listFiles(); // 列出目录下所有文件
        if (files == null) { // 目录为空
            return;
        }
        for (File cur : files) {
            if (cur.isDirectory()) { // 如果是目录
                searchDirectory(cur, srcName);
            } else { // 不是目录, 即文件
                deleteDirectory(cur, srcName);
            }
        }
    }

    private static void deleteDirectory(File file, String srcName) {
        if (! file.getName().contains(srcName)) { // 如果文件不含有目标字符
            System.out.println("shit");
            return ;
        }
        try {
            System.out.println("该文件为: " + file.getName());
            System.out.println("路径为: " + file.getCanonicalPath());
            System.out.println("是否需要删除 ? (Y / N)");
            Scanner in = new Scanner(System.in);
            String choice = in.next();
            if (choice.equals("Y")) {
                file.delete();
                System.out.println("删除成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
